package Algorithms.classic;

import java.util.Arrays;
import java.util.Random;
import java.util.function.UnaryOperator;

/**
 * description: <br>
 * createTime: 2018/11/617:06 <br>
 *
 * @author zzh
 */
public class SortUtils {
    private static Random rand = new Random();

    public static int[] createRandomArray(int length, int max) {
        int[] result = new int[length];
        for (int i = 0; i < length; i++) {
            result[i] = rand.nextInt(max);
        }
        return result;
    }

    public static boolean isSorted(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] > array[i + 1]) {
                return false;
            }
        }
        return true;
    }


    public static boolean equalIgnorePosition(int[] array1, int[] array2) {
        Arrays.sort(array1);
        Arrays.sort(array2);
        return Arrays.equals(array1, array2);
    }

    /**
     * 交换算法
     * @param array
     * @param index1
     * @param index2
     */
    public static void swap(int[] array, int index1, int index2) {
        array[index1] ^= array[index2];
        array[index2] ^= array[index1];
        array[index1] ^= array[index2];
    }

    public static void test(UnaryOperator<int[]> sortFunction) {
        int[] array;
        for (int i = 0; i < 10000; i++) {
            for (int length = 5; length < 10; length++) {
                array = SortUtils.createRandomArray(length, 100);
                int[] temp = array.clone();
                sortFunction.apply(temp);
                boolean result1 = SortUtils.isSorted(temp);
                boolean result2 = SortUtils.equalIgnorePosition(array, temp);
                if (!result1 || !result2) {
                    System.out.println("isSorted: " + result1);
                    System.out.println("equals: " + result2);
                    System.out.println(false);
                    return;
                }
            }
        }
        System.out.println("over");
    }
}
